package com.tanhua.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.PublishScore;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RocketMQMessageListener(topic = "tanhua-quanzi", consumerGroup = "tanhua-quanzi-consumer")
public class PublishScoreListener implements RocketMQListener<String> {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void onMessage(String message) {
        // 1.解析消息
        Map<String, Object> map = JSON.parseObject(message, Map.class);
        Integer type = Integer.valueOf(map.get("type").toString());
        Long userId = Long.valueOf(map.get("userId").toString());
        String publishId = (String) map.get("publishId");
        Long pid = Long.valueOf(map.get("pid").toString());

        // 2.创建评分数据对象
        PublishScore publishScore = new PublishScore();
        publishScore.setUserId(userId);
        publishScore.setPublishId(pid);
        publishScore.setDate(System.currentTimeMillis());

        // 3.计算得分
        // type 1-发动态，2-浏览动态， 3-点赞， 4-喜欢， 5-评论，6-取消点赞，7-取消喜欢
        switch (type) {
            case 1:
                Double score = 0D;
                Publish publish = mongoTemplate.findById(new ObjectId(publishId), Publish.class);
                if (publish.getTextContent().length() < 50) {  // 文字长度小于50
                    score += 1;
                } else if (publish.getTextContent().length() < 100) { // 文字长度大于等于50，小于100
                    score += 2;
                } else {
                    score += 3;
                }
                // 一张图片加一分
                if (publish.getMedias() != null) {
                    score += publish.getMedias().size();
                }
                publishScore.setScore(score);
                break;

            case 2:
                publishScore.setScore(1D);
                break;

            case 3:
                publishScore.setScore(5D);
                break;

            case 4:
                publishScore.setScore(8D);
                break;

            case 5:
                publishScore.setScore(10D);
                break;

            case 6:
                publishScore.setScore(-5D);
                break;

            case 7:
                publishScore.setScore(-8D);
                break;
        }

        // 保存评分数据到mongoDB
        mongoTemplate.save(publishScore);

    }


}
